package com.example.systemserver.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.server.HttpServerResponse;
import com.example.systemserver.bean.ResultBean;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    @RequestMapping("/upload")
    public ResultBean upload(@RequestParam("files") MultipartFile file) throws IOException {
        //file就是传递过来的文件
        //获取图片的后缀名，生成唯一的名称。
        String filename = file.getOriginalFilename();
        //获取文件名
        String suffix = filename.substring(filename.lastIndexOf("."));
        String newFileName = IdUtil.getSnowflakeNextIdStr() + suffix;
        file.transferTo(new File("C:\\Users\\Administrator\\Desktop\\images\\"+newFileName));
        String imagePath = "http://localhost:8080/file/getImage/"+newFileName;
        return new ResultBean(200, "上传成功", imagePath);
    }
    //filename为未知的，所以用@PathVariable获取
    @RequestMapping("/getImage/{filename}")
    public void getImage(@PathVariable String filename , HttpServletResponse response)throws Exception{
        log.info("/file/getImage获取目录，请求参数:{}",filename);
        //找到该文件
        File file = new File("C:\\Users\\Administrator\\Desktop\\images\\"+filename);
        //流读取
        InputStream in = new FileInputStream( file);
        //获取到通向浏览器的输出流
        OutputStream out = response.getOutputStream();
        IoUtil.copy(in,out);
    }
}
